/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlers;

import Pojos.ThanhVien;
import Util.MyUtil;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author ToanNhan
 */
@WebServlet(name = "DangNhap", urlPatterns = {"/DangNhap"})
public class DangNhap extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String command = request.getParameter("command");
            if (command == null || command.length() == 0) {
                response.sendRedirect("/WebsiteBanHang/DangNhap.jsp");
            } else {
                command = command.toLowerCase();
                if (command.compareTo("dangnhap") == 0) {
                    DangNhap(request, response, out);
                }

                if (command.compareTo("dangnhapbangcookie") == 0) {
                    DangNhapBangCookie(request, response, out);
                }

                if (command.compareTo("dangxuat") == 0) {
                    DangXuat(request, response, out);
                }
            }

        } finally {
            out.close();
        }
    }

    protected boolean DangNhapBangCookie(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws IOException {
        boolean result = false;
        Cookie[] arr = request.getCookies();
        String tenDangNhap = "";
        String matKhau = "";
        for (Cookie cookie : arr) {
            String cookieName = cookie.getName().toLowerCase();
            if (cookieName.compareTo("userName") == 0) {
                tenDangNhap = cookie.getValue();
                continue;
            }
            if (cookieName.compareTo("password") == 0) {
                matKhau = cookie.getValue();
            }
        }
        if (tenDangNhap == null){
            return false;
        }
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        Query query = session.createQuery("from ThanhVien where userName=?");
        query.setString(0, tenDangNhap);
        ThanhVien tv = (ThanhVien) query.uniqueResult();
        if (tv == null) {
            //send ket qua ve
        } else {
            if (tv.getPassword().compareTo(matKhau) == 0) {
                //Dang nhap thanh cong
                System.out.println("Thanh vien: " + tv.getUserName() + " dang nhap thanh cong");
                int soTinNhan = 0;
                if (tv.getTinnhansForNguoiNhan() != null) {
                    soTinNhan = tv.getTinnhansForNguoiNhan().size();
                }
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute("hoTen", tv.getHoTen());
                httpSession.setAttribute("soTinNhan", soTinNhan);
                httpSession.setAttribute("isLogin", true);
                httpSession.setAttribute("userName", tv.getUserName());
                httpSession.setAttribute("nhomThanhVien", tv.getNhomThanhVien().getMaNhomThanhVien());
                String json = "{\"hoTen\":\"" + tv.getHoTen() + "\",\"soTinNhan\":\"" + soTinNhan + "\"}";
                out.write(json);
                out.flush();
                out.close();
                session.close();
                factory.close();
                if (httpSession.getAttribute("lastPage") != null) {
                    String lastPage = (String) httpSession.getAttribute("lastPage");
                    response.sendRedirect(lastPage);
                }
                return true;
            }
        }
        return result;
    }

    protected void DangNhap(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws IOException {
        response.setContentType("application/json");
        String tenDangNhap = request.getParameter("tenDangNhap");
        String matKhau = request.getParameter("matKhau");
        String err = "";
        if (tenDangNhap == null || tenDangNhap.length() == 0) {
            err = "Bạn chưa nhập tên đăng nhập\n";
        }
        if (matKhau == null || matKhau.length() == 0) {
            err += "Bạn chưa nhập mật khẩu";
        }

        if (err.length() == 0) {
            SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
            Session session = factory.openSession();
            Query query = session.createQuery("from ThanhVien where userName=?");
            query.setString(0, tenDangNhap);
            ThanhVien tv = (ThanhVien) query.uniqueResult();
            if (tv == null) {
                DangNhapBangCookie(request, response, out);
            } else {
                matKhau = MyUtil.maHoaMD5(matKhau);
                if (tv.getPassword().compareTo(matKhau) == 0) {
                    //Dang nhap thanh cong
                    System.out.println("Thanh vien: " + tv.getUserName() + " dang nhap thanh cong");
                    int soTinNhan = 0;
                    if (tv.getTinnhansForNguoiNhan() != null) {
                        soTinNhan = tv.getTinnhansForNguoiNhan().size();
                    }
                    HttpSession httpSession = request.getSession();
                    httpSession.setAttribute("hoTen", tv.getHoTen());
                    httpSession.setAttribute("soTinNhan", soTinNhan);
                    httpSession.setAttribute("isLogin", true);
                    httpSession.setAttribute("userName", tv.getUserName());
                    String json = "{\"hoTen\":\"" + tv.getHoTen() + "\",\"soTinNhan\":\"" + soTinNhan + "\"}";
                    out.write(json);
                    out.flush();
                    out.close();
                    session.close();
                    factory.close();
                    boolean ghiNho = Boolean.valueOf(request.getParameter("ghiNho"));
                    if (ghiNho) {
                        Cookie userNameCookie = new Cookie("userName", tenDangNhap);
                        Cookie passwordCookie = new Cookie("password", matKhau);

                        userNameCookie.setMaxAge(3600 * 24 * 365);
                        passwordCookie.setMaxAge(3600 * 24 * 365);
                        response.addCookie(passwordCookie);
                        response.addCookie(userNameCookie);
                    }
                    if (httpSession.getAttribute("lastPage") != null) {
                        String lastPage = (String) httpSession.getAttribute("lastPage");
                        response.sendRedirect(lastPage);
                    }
                }
            }
        }
    }

    protected void DangXuat(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("hoTen", null);
        httpSession.setAttribute("soTinNhan", null);
        httpSession.setAttribute("isLogin", false);
        httpSession.setAttribute("userName", null);
        Cookie[] arr = request.getCookies();
        for (Cookie cookie : arr) {
            String cookieName = cookie.getName().toLowerCase();
            if (cookieName.compareTo("username") == 0) {
                cookie.setMaxAge(-1);
                continue;
            }
            if (cookieName.compareTo("password") == 0) {
                cookie.setMaxAge(-1);
            }
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
